<template>
  <div style="width: 100%;" v-loading="loading">
    <div class="top-bar">
      <div class="item" style="margin-top: 10px">
        <el-tooltip class="item" effect="dark" content="重新加载数据" placement="top">
          <a href="#" @click="getData"><i class="el-icon-refresh"></i></a>
        </el-tooltip>
      </div>
      <div class="item">
        <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 245px;height: 40px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="getData"/>
      </div>
    </div>
    <div class="chart-div" ref="chart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {getLastDate, queryTemp} from "@/api/raw";
import {addDays} from "@/utils/common";

export default {
  name: "tempChart",
  props: ["pointCode"],
  data() {
    return {
      loading: false,
      // 图表对象
      chart: null,
      // 图表配置
      chartOptions: null,
      // 图表数据
      chartData: {
        eventTime: [],
        tempData: [],
      },
      dateRange: [],
      vibForm: {
        pointCode: null,
      }
    }
  },
  watch: {
    pointCode: {
      handler: function (val) {
        this.$nextTick(() => {
          this.vibForm.pointCode = val;
          this.getLastDate();
        })
      },
      immediate: true
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', () => {
      this.chart.resize()
    })
  },
  methods: {
    async getLastDate() {
      this.loading = true;
      if (!this.pointCode) {
        this.showEmptyChart();
        return;
      }
      let res = await getLastDate(this.pointCode);
      if (res.data != null) {
        let endTime = this.parseTime(res.data, '{y}-{m}-{d}');
        let beginTime = this.parseTime((res.data - 3600 * 1000 * 1000 * 24 * 30), '{y}-{m}-{d}');
        this.dateRange = [beginTime, endTime];
      } else {
        const today = new Date();
        this.dateRange = [this.parseTime(addDays(today, -7).getTime(), '{y}-{m}-{d}'), this.parseTime(today.getTime(), '{y}-{m}-{d}')];
      }
      this.getData();
    },
    getData() {
      this.vibForm = this.addDateRange(this.vibForm, this.dateRange);
      queryTemp(this.vibForm).then(res => {
        if (res.data) {
          this.chartData.eventTime = res.data.eventTime;
          this.chartData.tempData = res.data.temperature;
          this.loadData();
        }
      }).catch(err => {
        this.showEmptyChart()
      })
    },
    showEmptyChart(){
      this.chartOptions.xAxis[0].data = [];
      this.chartOptions.series[0].data = [];
      this.chart.setOption(this.chartOptions, true);
      this.chart.showLoading({
        text: '暂无数据',
        showSpinner: false,
        textColor: '#808080',
        // maskColor: 'rgba(0, 0, 0, .2)',
        fontSize: '26px',
        fontWeight: '400'
      })
      this.loading = false;
    },
    loadData() {
      if (this.chartData == null || this.chartData.eventTime.length === 0) {
        this.showEmptyChart();
        return;
      }
      this.chartOptions.xAxis[0].data = this.chartData.eventTime;
      this.chartOptions.series[0].data = this.chartData.tempData;
      this.chart.setOption(this.chartOptions, true);
      this.chart.hideLoading();
      this.loading = false;
    },
    /**
     * 初始化图表
     */
    initChart() {
      if (this.chart !== null && this.chart !== undefined) {
        this.chart.dispose();
      }
      this.chartOptions = {
        color: ['#28b1e4'],
        dataZoom: [{
          type: 'inside',
          show: true
        }],
        legend: {
          textStyle: {}
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
          crossStyle: {
            color: "#04214e",
          },
          showContent: true,
          // formatter:(params)=>{
          //   return params[0].name +'</br>'+
          //     params[0].seriesName+':'+params[0].data+'dB'+'</br>'+
          //     params[1].seriesName+':'+params[1].data+'KB'+'</br>'
          // }
        },
        xAxis: [
          {
            name: '时间',
            nameLocation: 'center',
            nameTextStyle: {
              padding: [10, 0, 0, 0]
            },
            type: 'category',
            axisTick: {
              alignWithLabel: true,
              lineStyle: {},
              interval: 100
            },
            axisLine: {
              show: true,
              lineStyle: {}
            },
            splitLine: {
              lineStyle: {}
            },
            axisPointer: {
              lineStyle: {
                color: "#E6A23C"
              },
              label: {
                formatter: function (params) {
                  if (params.seriesData[0].data) {
                    // return "[x]" + params.value + "  [y]" + params.seriesData[0].data[1] + "m/s^2";
                    return params.value;
                  } else {
                    return null;
                  }
                },
                padding: [5, 14],
                margin: 0,
                backgroundColor: "#E6A23C"
              },
            },
          }
        ],
        yAxis: [
          {
            name: '表面温度',
            // nameLocation: 'end',
            type: 'value',
            // boundaryGap: ["20%", '20%'],
            position: "left",
            splitLine: {
              lineStyle: {}
            },
            axisLine: {
              show: true,
              lineStyle: {}
            },
            axisLabel: {
              inside: false,
              formatter: "{value}℃",
            },
            axisPointer: {
              lineStyle: {
                color: "#E6A23C"
              },
              label: {
                backgroundColor: "#E6A23C"
              }
            },
            axisTick: {
              inside: true,
            }
          }
        ],
        grid: {
          top: 30,
          bottom: 20,
          left: 10,
          right: 10,
          containLabel: true,
        },
        series: [
          {
            name: '表面温度',
            type: 'line',
            // itemStyle: {
            //   color: 'rgb(255,10,10)'
            // },
            symbol: "circle",
            symbolSize: 10,
            xAxisIndex: 0,
            yAxisIndex: 0,
            lineStyle: {
              width: 1,
              // color: "#409EFF",
            },
            emphasis: {
              lineStyle: {
                width: 1
              }
            },
            markLine: {
              symbol: 'circle',
              label: {
                normal: {
                  position: 'end',
                  formatter: function (e) {
                  }
                }
              },
              data: []
            }
          }
        ]
      };
      this.chart  = echarts.init(this.$refs.chart);
      this.chart.setOption(this.chartOptions);
      let that = this;
      onOrientationChange(function () {
        that.chart.resize();
      });
    },
  }
}
//图表重加载
var onOrientationChange = function (cb) {
  var evt = "onorientationchange" in window ? "orientationchange" : "resize";
  window.addEventListener(evt, resize, true);

  function resize(fals) {
    if (window.orientation == 0 || window.orientation == 180) {
      cb('v');
    } else {
      cb('h');
    }
  }

  resize(true);
}
</script>

<style scoped>
.top-bar {
  margin-bottom: 20px !important;
  display: flex;
}

.top-bar > .item {
  margin: 0 0 0 10px;
}
.chart-div {
  width: 100%;
  height: 350px;
}
</style>